import { uploadImg } from '@/api/api'
import Compressor from 'compressorjs'
export const compress = (file, loading, photos) => {
  loading.value = true
  if (file.size > 1024 * 1024 * 2) {
    new Compressor(file, {
      quality: 0.4,
      success(compressedBlob) {
        let compressedFile = new File([compressedBlob], Math.random().toString(36).slice(-8), {
          type: file.type
        })
        console.log(compressedFile.size)
        if (compressedFile.size > 1024 * 1024 * 2) {
          const deleteIndex = photos.findIndex((item) => item.uid === file.uid)
          photos.splice(deleteIndex, 1)
          loading.value = false
          ElMessage({
            message: '图片大于2M，请重新上传图片！',
            type: 'error'
          })
        } else {
          const formData = new FormData() //构造一个 FormData，把后台需要发送的参数添加
          formData.append('file', compressedFile) //接口需要传的参数
          uploadImg(formData).then((res) => {
            const curPhoto = photos.find((item) => item.uid === file.uid)
            curPhoto.url = res.url
            curPhoto.status = 'success'
            // photos.find((item) => item.uid === file.uid).url = res.url
            loading.value = false
            ElMessage({
              message: '图片上传成功！',
              type: 'success'
            })
          })
        }
      },
      error(err) {
        const deleteIndex = photos.findIndex((item) => item.uid === file.uid)
        photos.splice(deleteIndex, 1)
        loading.value = false
        ElMessage({
          message: '图片上传失败！',
          type: 'error'
        })
        console.log('compress error: ', err.message)
      }
    })
  } else {
    new Compressor(file, {
      quality: 0.8,
      success(compressedBlob) {
        let compressedFile = new File([compressedBlob], Math.random().toString(36).slice(-8), {
          type: file.type
        })
        console.log(compressedFile.size)
        const formData = new FormData() //构造一个 FormData，把后台需要发送的参数添加
        formData.append('file', compressedFile) //接口需要传的参数
        uploadImg(formData).then((res) => {
          const curPhoto = photos.find((item) => item.uid === file.uid)
          curPhoto.url = res.url
          curPhoto.status = 'success'
          // photos.find((item) => item.uid === file.uid).url = res.url
          loading.value = false
          ElMessage({
            message: '图片上传成功！',
            type: 'success'
          })
        })
      },
      error(err) {
        const deleteIndex = photos.findIndex((item) => item.uid === file.uid)
        photos.splice(deleteIndex, 1)
        loading.value = false
        ElMessage.error('上传文件格式务必PNG|JPG！')
        console.log('compress error: ', err.message)
      }
    })
  }
}

